<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="商品类型" prop="goodsType">
        <el-select v-model="queryParams.goodsType" placeholder="请选择商品类型" clearable size="small">
          <el-option
            v-for="dict in goodsTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select v-model="queryParams.goodsStatus" placeholder="请选择商品状态" clearable size="small">
          <el-option
            v-for="dict in goodsStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品编号" prop="goodsSn">
        <el-input
          v-model="queryParams.goodsSn"
          placeholder="请输入商品编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable size="small">
          <el-option
            v-for="dict in categoryOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['content:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['content:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['content:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['content:goods:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类" align="center" prop="id" />
      <el-table-column label="商品名" align="center" prop="goodsName" />
      <el-table-column label="商品类型" align="center" prop="goodsType" :formatter="goodsTypeFormat" />
      <el-table-column label="商品说明" :show-overflow-tooltip="true" align="center" prop="goodsDesc" />
      <el-table-column label="商品状态" align="center" prop="goodsStatus" :formatter="goodsStatusFormat" />
      <el-table-column label="商品价钱" align="center" prop="goodsPrice" />
      <el-table-column label="商品折扣价" align="center" prop="discountPrice" />
      <el-table-column label="运费" align="center" prop="expressFee" />
      <el-table-column label="商品图片"  align="center" :show-overflow-tooltip="true" prop="goodsImage" />
      <el-table-column label="商品明细" :show-overflow-tooltip="true" align="center" prop="goodsDeatail" />
      <el-table-column label="商品编号" align="center" prop="goodsSn" />
      <el-table-column label="分类" align="center" prop="category" :formatter="categoryFormat" />
      <el-table-column label="商品数量" align="center" prop="num" />
      <el-table-column label="初始化库存" align="center" prop="initNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['content:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['content:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名" prop="goodsName">
          <el-input v-model="form.goodsName" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="form.goodsType" placeholder="请选择商品类型">
            <el-option
              v-for="dict in goodsTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品说明" prop="goodsDesc">
          <el-input v-model="form.goodsDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-radio-group v-model="form.goodsStatus">
            <el-radio
              v-for="dict in goodsStatusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品价钱" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价钱" />
        </el-form-item>
        <el-form-item label="商品折扣价" prop="discountPrice">
          <el-input v-model="form.discountPrice" placeholder="请输入商品折扣价" />
        </el-form-item>
          <el-form-item label="运费" prop="goodsName">
          <el-input v-model="form.expressFee" type="textarea" placeholder="请输入运费" />
        </el-form-item>
      <el-form-item label="商品图片" prop="poster">
            <el-upload
              :headers="videoUpload.headers"
              :action="videoUpload.url"
              :file-list="goodsPhotoList"
              list-type="picture-card"
              :before-upload="limit"
              :on-success="success"
              :on-preview="preview"
              :on-remove="remove"
              accept=".jpg,.jpeg,.png,,.JPG,.JPEG"
              :limit="10">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        <el-form-item label="商品明细" prop="goodsDeatail">
          <el-input v-model="form.goodsDeatail" type="textarea" placeholder="请输入内容" />
    <!-- <tinymceeditor v-model="content" ref="form.goodsDeatail"></tinymceeditor> -->

    <!-- <vue-editor id="editor" :editorToolbar="customToolbar" useCustomImageHandler  @image-added="handleImageAdded" v-model="form.goodsDeatail"> </vue-editor> -->
    <!-- <div style="display:flex">
      <div style="width: 50%;"><vue-editor :customModules="customModulesForEditor"  useCustomImageHandler  @image-added="handleImageAdded" :editorToolbar="customToolbar" :editorOptions="editorSettings" v-model="form.goodsDeatail"> </vue-editor>
       </div>
      <div style="width: 50%;">
         <div style="width: 50%;" class="content" v-html="form.goodsDeatail"></div>
      </div>
    </div> -->
        </el-form-item>
        <!-- <el-form-item label="分类">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="dict in categoryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="商品数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入商品数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, exportGoods } from "@/api/content/goods";
 import { getToken } from '@/utils/auth'
import { VueEditor } from "vue2-editor";
import axios from "axios";

import { ImageDrop } from "quill-image-drop-module";
import ImageResize from "quill-image-resize-module";


export default {
  name: "Goods",
  　components: {VueEditor},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商品类型字典
      goodsTypeOptions: [],
      // 商品状态 0 待上架 1上架 2 下架字典
      goodsStatusOptions: [],
      // 分类字典
      categoryOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsType: undefined,
        goodsStatus: undefined,
        goodsDeatail: undefined,
        goodsSn: undefined,
        category: undefined,
      },
      // 表单参数
      form: {
        expressFee:0
      },
      // 表单校验
      rules: {
      }, 
       videoUpload:{
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sys/file/upload",
        url2: process.env.VUE_APP_BASE_API,
      },
      goodsPhotoList:[],
        t1:[],
              // customToolbar: [
              //   ["bold", "italic", "underline"],
              //  [{ list: "ordered" }, { list: "bullet" }], 
              // ["image", "code-block"],
              // []],
                        customToolbar: [
  [{ header: [false, 1, 2, 3, 4, 5, 6] }],
  [{ size: ["small", false, "large", "huge"] }],
  ["bold", "italic", "underline", "strike"],
  [
    { align: "" },
    { align: "center" },
    { align: "right" },
    { align: "justify" }
  ],
  [{ header: 1 }, { header: 2 }],
  ["blockquote", "code-block"],
  [{ list: "ordered" }, { list: "bullet" }, { list: "check" }],
  [{ indent: "-1" }, { indent: "+1" }],
  [{ color: [] }, { background: [] }],
  ["link", "image", "formula"],
  [{ direction: "rtl" }],
  ["clean"]],
      customModulesForEditor: [{ alias: "imageDrop", module: ImageDrop }, { alias: "imageResize", module: ImageResize }],
      editorSettings: {
        modules: {
          imageDrop: true,
          imageResize: {
            displayStyles: {
                backgroundColor: 'black',
                border: 'none',
                color: 'white',
                width:'100%'
            }
          }
        }
      },
       msg: 'Welcome to Use Tinymce Editor',
       disabled: false

    };
  },
  created() {
    this.getList();
    this.getDicts("sys_good_type").then(response => {
      this.goodsTypeOptions = response.data;
    });
    this.getDicts("sys_good_status").then(response => {
      this.goodsStatusOptions = response.data;
    });
    this.getDicts("sys_good_type").then(response => {
      this.categoryOptions = response.data;
    });
  },
  methods: {
    // 鼠标单击的事件
    onClick (e, editor) {
      console.log('Element clicked')
      console.log(e)
      console.log(editor)
    },
    // 清空内容
    clear () {
      this.$refs.editor.clear()
    },
   handleImageAdded:function(file, Editor, cursorLocation, resetUploader){
// An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)

      var formData = new FormData();
      formData.append("image", file);

      axios({
        url: this.videoUpload.url,
        method: "POST",
        headers:this.videoUpload.headers,
        data: formData
      })
        .then(result => {
          console.log(result)
          let url = result.data.url; // Get url from response
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        })
        .catch(err => {
          console.log(err);
        });
   },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 商品类型字典翻译
    goodsTypeFormat(row, column) {
      return this.selectDictLabel(this.goodsTypeOptions, row.goodsType);
    },
    // 商品状态 0 待上架 1上架 2 下架字典翻译
    goodsStatusFormat(row, column) {
      return this.selectDictLabel(this.goodsStatusOptions, row.goodsStatus);
    },
    // 分类字典翻译
    categoryFormat(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        goodsName: undefined,
        goodsType: undefined,
        goodsDesc: undefined,
        goodsStatus: "0",
        userId: undefined,
        userName: undefined,
        goodsPrice: undefined,
        discountPrice: undefined,
        createTime: undefined,
        updateTime: undefined,
        goodsImage: undefined,
        goodsDeatail: undefined,
        goodsSn: undefined,
        category: undefined,
        num: undefined,
        initNum: undefined,
        goodsPhotoList:[],
        t1:[],
        expressFee:0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
         this.goodsPhotoList=[],
      this.title = "添加商品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
         this.goodsPhotoList = JSON.parse(response.data.goodsImage).map(item => {
          return {
            url: item
          }
        });
        this.title = "修改商品管理";
        this.t1 = JSON.parse(response.data.goodsImage);
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
         this.form.goodsDeatail = this.form.goodsDeatail
        if (valid) {
          if (this.form.id != undefined) {
             this.form.goodsImage = JSON.stringify(this.t1);
               console.log(this.form)
            updateGoods(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            this.form.goodsImage = JSON.stringify(this.t1);
               console.log(this.form)
            addGoods(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportGoods(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
     success:function(res, file){
       console.log(this.goodsPhotoList)
        this.goodsPhotoList.push(file)
        this.t1.push(file.response.url)
        console.log(this.t1)
    },
        preview:function(file) {
      console.log("预览")
      console.log(file.url)
      //  this.dialogImageUrl = file.url;
      //  this.dialogVisible = true;
    },
    
    remove:function(file, fileList){
      console.log(fileList)
      console.log(file);
      this.goodsPhotoList = fileList;
      this.t1 =[];
      for(var i =0;i<fileList.length;i++){
       this.t1.push(fileList[i].url)
      }
       console.log(this.t1)
    },
    limit:function(file){
          if(this.goodsPhotoList.length>10){
            this.msgInfo("最多上传10张图片")
          }
    },
        getUrl(v){
      var  arr = new Array();
      for (var i =0;i<v.length;i++){
        console.log("是否存在"+v[i].response)
         if (v[i].response==null||v[i].response==undefined){
           arr.push(v[i].url)
         }else {
           arr.push(v[i].response.url)
         }
      }
      return arr;
    },
  },
     
};
</script>
<style rel="stylesheet/scss" lang="scss">
image{
  width: 100%;
}

</style>
